// timeSDK
import 'package:app_info/info/appsflyer.dart';
import 'package:flutter/cupertino.dart';
import 'package:giraffe/giraffe.dart';
import 'package:smartloan_mdc/extension/extension.dart';
import 'package:smartloan_mdc/http/api/api.dart';
import 'package:smartloan_mdc/res/string.dart';
import '../javascript_channel.dart';

class TimeSdk extends JavaScriptChannel implements GiraffeCallback {
  @override
  List<String> get actions => ['timeSDK', 'timeSDK2'];

  @override
  onReceive(Map newMsg) {
    // onMessageReceive ===>
    // {"action":"timeSDK","id":"0.6438988499401284",
    // "data":{"orderNo":"8aaf10f2-732b-47f5-988b-a1680ff02d36","userId":"1714599127314210816","step":2,"isSubmit":false,"appList":false,"sms":false,"exif":false,"device":false,"contact":false,"calendar":true,"callLog":true,"location":false},"callback":"webViewToTime"}
    if (newMsg['action'] == 'timeSDK2') {
      newMsg['data']['orderNo'] = '8in1';
    }
    Giraffe().start(this, newMsg['data']);
  }

  @override
  onAfLog(String msg) {
    debugPrint('afmsg $msg');
    AppsFlyer().logEvent(msg);
  }

  @override
  onFail(bool isSubmit, int step, String orderNo, Map dataMap) {
    debugPrint('sdk onFail: isSubmit: $isSubmit, step: $step');
    if (isSubmit && (step == 4)) {
      // 需要回调与重传
      callBack(false, {});
    }
  }

  @override
  onPermissionHint() {
    // debugPrint('permission hint');
    AppStr.permissionObtain.toast();
  }

  @override
  onSuccess(bool isSubmit, int step, String filePath, String md5, String orderNo, Map dataMap) {
    debugPrint('sdk onSuccess: isSubmit: $isSubmit, step: $step, filePath: $filePath, md5: $md5');
    if (isSubmit && (step == 4)) {
      // 需要回调与重传
      uploadFile(md5, orderNo, filePath, 3);
    } else {
      uploadFile(md5, orderNo, filePath, 1);
    }
  }

  uploadFile(String md5, String orderNo, String filePath, int reload) async {
    if (reload < 1) return;
    try {
      await RequestApi().zip6in1(md5, orderNo, filePath);
      callBack(true, {});
    } on Exception catch (e) {
      debugPrint("upload file error ${e.toString()}");
      uploadFile(md5, orderNo, filePath, (reload - 1));
    }

  }

}